<?php

require_once('MagicBean.php');


class FormHandler {
	
	private $fields;
	
	
	public function __construct() {
		$this->fields = array();
	}
	
	public function addField($n, $t, $req = false, $val = '') {
		
		$this->fields[] = new MagicField($n, $t, $req, $val);
		
	}
	
	public function readRequest($request) {
		
		foreach ($this->fields as $f) {
			$f->value($request->get($f->name()));
		}
	}
	
	public function validate() {
		$notValidFields = array();
		global $DataTypes;
		
		foreach ($this->fields as $f) {
			
			if ($f->required() && (trim($f->value()) == '') ) {
				$notValidFields[] = $f->name();
			} else if ($f->required() || ($f->value() != '') ) {
				if (!$DataTypes->validate($f->type(), $f->value())) {
					$notValidFields[] = $f->name();
				}
			}
		}
		
		$res = new MagicBean();
		
		if (empty($notValidFields)) {
			$res->Result(true);
		} else {
			$res->Result(false);
			$res->Errors($notValidFields);
		}
		
		return $res;
	}
	
	public function writeResponse($response) {
		foreach ($this->fields as $f) {
			$response->set($f->name(), $f->value());
		}		
	}
	
}



class MagicField extends MagicBean{
	
	public function __construct($n, $t, $req, $val)  {
		$this->params['name'] = $n;
		$this->params['type'] = $t;
		$this->params['value'] = $val;
		$this->params['required'] = $req;
	}	
	
}


class Field {

	protected $name;
	protected $value;
	protected $type;
	protected $required;
	
	public function __construct($n, $t, $req = false, $val = '')  {
		$this->name = $n;
		$this->type = $t;
		$this->value = $val;
		$this->required = $req;
	}
	
	public function type() {
		$args = func_get_args();
		if (count($args) == 0)  {
			return $this->type;
		}
		$this->type = $args[0];
	}
	
	public function val() {
		$args = func_get_args();
		if (count($args) == 0)  {
			return $this->val;
		}
		$this->val = $args[0];
	}
	
	public function required() {
		$args = func_get_args();
		if (count($args) == 0)  {
			return $this->required;
		}
		$this->required = $args[0];
	}	
}